import getApiData, { getNestApiData } from '@/services/cpasRequest';
import { nanoid10 } from '@/utils';
import { msgError } from '@/utils/msg';
import { formatNumber } from 'devextreme/localization';
import { consts } from '../../consts';
import {
  LayerRange,
  ProjectOverallProps,
  SampledResult,
  SampleField,
  SampleMethod,
  SampleParameterValues,
  SampleSizeAndAmount,
  SampleSortField,
  SampleStepInfo,
  SampleTable,
  SystemExtractType,
} from '../../typing';
import { getSampleOverallWhereSQL } from '../samplingProjectOverallService';
import { getNanoid10, getRealTableName, showNotDataMsg } from '../service';
import { calcRangeValues, getLayerSampleList } from './SampleMethod/LayerSampleService';
import {
  getNotReproRandomValues,
  getReproducibleRandomValues,
} from './SampleMethod/RandomSampleService';
import {
  getPPSSampleList,
  getRandomOrSystemSampleList,
  getSystemSampleNos,
  getSystemSortFields,
} from './SampleMethod/SystemSampleService';

export function enumToStringArray<T extends string>(enumType: Record<string, T>): T[] {
  return Object.values(enumType) as T[];
}

export function getDefaultSampleSortFields(projectOverallProps?: ProjectOverallProps) {
  const curSampleTable = projectOverallProps?.curSampleTable;
  let sortFieldsArray: SampleSortField[] = [
    { fieldName: '', sortType: 'asc', isAbs: false },
    { fieldName: '', sortType: 'asc', isAbs: false },
    { fieldName: '', sortType: 'asc', isAbs: false },
  ];
  let sampleNumFieldsArray: string[] = curSampleTable?.sampleNumFieldsArray || [];
  //凭证表,界面查询(非高级查询条件)
  /*  if (curSampleTable?.isVoucher && !projectOverallProps?.curWhereSqlParams?.isAdvQuery) {
     const jeFx = projectOverallProps?.curWhereSqlParams?.formQueryParams.jeFx;
     if (jeFx == consts.JF_DF_Text) {
       sampleNumFieldsArray = [consts.JFJE_DFJE_Field];
     } else if (jeFx == consts.JF_Text) {
       sampleNumFieldsArray = [consts.JFJE_DFJE_Array[0]];
     } else if (jeFx == consts.DF_Text) {
       sampleNumFieldsArray = [consts.JFJE_DFJE_Array[1]];
     }
   }
  */
  if (curSampleTable?.isVoucher) {
    if (sampleNumFieldsArray.filter(item => consts.JFJE_DFJE_Array.includes(item)).length
      == consts.JFJE_DFJE_Array.length) {
      sampleNumFieldsArray = [consts.JFJE_DFJE_Field];
    }
  }
  if (sampleNumFieldsArray.length) {
    sampleNumFieldsArray.forEach((item, index) => {
      if (index == 0 && !sortFieldsArray[index].fieldName) {
        //只取1个
        sortFieldsArray[index].fieldName = item;
        sortFieldsArray[index].sortType = 'desc';
      }
    });
  } else {
    if (curSampleTable?.sortFieldsArray.length) {
      sortFieldsArray
        .filter((item) => !item.fieldName)
        .forEach((item, index) => {
          if (index < 2 && curSampleTable?.sortFieldsArray.length >= index) {
            sortFieldsArray[index].fieldName = curSampleTable?.sortFieldsArray[index];
          }
        });
    }
  }

  return sortFieldsArray;
}

export function getNumToChinese(num: number): string {
  switch (num) {
    case 1:
      return '首要';
    case 2:
      return '次要';
    case 3:
      return '第三';
    case 4:
      return '第四';
    case 5:
      return '第五';
    default:
      return '第' + num;
  }
}

export const leftVerticalDivStyle = {
  alignItems: 'center', // 竖直居中
  justifyContent: 'center', // 水平居中，可选
  height: '100%', // 根据需要调整高度
  fontSize: 15,
  fontWeight: 'bold',
  width: 40,
  border: '1px solid #e5e5e5',
  paddingLeft: 10,
  paddingTop: 30,
  paddingRight: 10,
  backgroundColor: '#f5f5f5',
};
/**
 *
 * @param sampleStepInfo
 * @param toBeTestSampleSize 测试的总体数据
 * @param toBeTestAmountSum  总金额
 * @param measurementSampleSize  样本规模
 * @returns
 */
export function getDefaultLayerRanges(
  sampleStepInfo: SampleStepInfo,
  toBeTestSampleSize: number,
  toBeTestAmountSum: number,
  measurementSampleSize: number,
): LayerRange[] {
  let retArray: any[] = [];
  let lastItem_1;
  if (toBeTestAmountSum == 0 && toBeTestSampleSize == 0) {
    retArray.push({
      guid: nanoid10(),
      orderIndex: 1,
      rangeValue: 0,
      rangeText: '> 0',
      unSampleSize: toBeTestAmountSum,
    });
  } else {
    //注：分层抽样默认按待抽样总体的平均金额分两层，从上层选出2/3，从下层选出1/3；支持自定义修改，点击设置：
    //上层是大于均值的
    const avg = (toBeTestAmountSum / toBeTestSampleSize).toFixed(2);
    const firstNeedSampleSize = Math.round((measurementSampleSize * 1) / 3); //
    const firstItem = {
      guid: nanoid10(),
      orderIndex: 1,
      rangeValue: avg,
      needSampleSize: firstNeedSampleSize,
    };
    retArray.push(firstItem);

    lastItem_1 = {
      guid: nanoid10(),
      orderIndex: 2,
      rangeValue: -1,
      needSampleSize: measurementSampleSize - firstNeedSampleSize,
    };
  }

  calcRangeValues(retArray, sampleStepInfo, lastItem_1); //lastItem_1=undefined,最后一行的为rangValue为-1的新加行的needSampleSize为undefined

  return retArray;
}
/**
 * 获取金额重大的抽样项目
 * @param sampleParmeterValues
 */

export async function getTextFieldsSampleList(
  sampleStepInfo: SampleStepInfo,
  inWhereSql?: string,
  sortFields?: string[],
): Promise<any[]> {
  const projectOverallProps = sampleStepInfo.projectOverallProps;
  if (!projectOverallProps?.curSampleTable) return [];
  const fields = projectOverallProps?.curSampleTable.sampleTextFieldsArray;
  if (!sortFields) sortFields = projectOverallProps?.curSampleTable.sortFieldsArray;

  const curWhereSqlParams = sampleStepInfo.projectOverallProps?.curWhereSqlParams;
  const projectOverallWhhereSql = getSampleOverallWhereSQL(curWhereSqlParams as any); //项目总体的条件

  let whereSql = projectOverallWhhereSql + (inWhereSql || '');
  const retData = await getApiData('sample.getSampleSourceDataList', {
    dbname: curWhereSqlParams?.dbname,
    tableName: getRealTableName(projectOverallProps?.curSampleTable?.tableName, {
      data_id: projectOverallProps?.curDataId || '',
    }), //todo:要替换真值
    sortFields: projectOverallProps?.curSampleTable.sortFieldsArray
      .map((item) => `[${item}]`)
      .join(','),
    fields: fields ? fields.map((fieldName) => `[${fieldName}]`).join(',') : '*',
    pageIndex: 0,
    pageSize: consts.maxSampleCount,
    whereSql: whereSql,
  });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }
  return retData.data;
}

export async function getSampleListByWhereSql(
  sampleStepInfo: SampleStepInfo,
  inWhereSql?: string,
  sortFields?: string[],
): Promise<any[]> {
  const projectOverallProps = sampleStepInfo.projectOverallProps;
  if (!projectOverallProps?.curSampleTable) return [];
  const fields = projectOverallProps?.curSampleTable.sampleAllFieldsArray.map(
    (item) => item.fieldName,
  );
  if (!sortFields) sortFields = projectOverallProps?.curSampleTable.sortFieldsArray;

  const curWhereSqlParams = sampleStepInfo.projectOverallProps?.curWhereSqlParams;
  const projectOverallWhhereSql = getSampleOverallWhereSQL(curWhereSqlParams as any); //项目总体的条件

  let whereSql = projectOverallWhhereSql + (inWhereSql || '');
  const retData = await getApiData('sample.getSampleSourceDataList', {
    dbname: curWhereSqlParams?.dbname,
    tableName: getRealTableName(projectOverallProps?.curSampleTable?.tableName, {
      data_id: projectOverallProps?.curDataId || '',
    }), //todo:要替换真值
    sortFields: projectOverallProps?.curSampleTable.sortFieldsArray
      .map((item) => `[${item}]`)
      .join(','),
    fields: fields ? fields.map((fieldName) => `[${fieldName}]`).join(',') : '*',
    pageIndex: 0,
    pageSize: consts.maxSampleCount,
    whereSql: whereSql,
  });

  if (!retData.ok) {
    msgError(retData.data);
    return [];
  }
  return retData.data;
}
export function getIniSampleSizeAndAmount(): SampleSizeAndAmount {
  return { sampleSize: 0, amountSum: 0, sampledNumFields: {} };
}

/**
 *  获取样本数量和金额
 * @param sampleStepInfo
 * @param inWhereSql
 * @returns
 */
export async function getSampleSizeAndAmount(
  sampleStepInfo: SampleStepInfo,
  inWhereSql?: string,
): Promise<SampleSizeAndAmount> {
  const projectOverallProps = sampleStepInfo.projectOverallProps;
  const sampleSizeAndAmount = getIniSampleSizeAndAmount();

  if (!projectOverallProps?.curSampleTable) return sampleSizeAndAmount;
  const numFields = projectOverallProps?.curSampleTable.sampleNumFieldsArray || [];
  if (projectOverallProps?.curSampleTable.isVoucher && numFields.length == 0) {
    msgError('没有设置抽样金额字段,请在【样本源】中设置！');
    return sampleSizeAndAmount;
  }

  const curWhereSqlParams = sampleStepInfo.projectOverallProps?.curWhereSqlParams;
  const projectOverallWhereSql = getSampleOverallWhereSQL(curWhereSqlParams as any); //项目总体的条件

  let whereSql = projectOverallWhereSql + (inWhereSql || '');
  const retData = await getApiData('sample.getSampleSizeAndAmount', {
    dbname: curWhereSqlParams?.dbname,
    tableName: getRealTableName(projectOverallProps?.curSampleTable?.tableName, {
      data_id: projectOverallProps?.curDataId || '',
    }), //todo:要替换真值
    sortFields: projectOverallProps?.curSampleTable.sortFieldsArray
      .map((item) => `[${item}]`)
      .join(','),
    sumFields: numFields
      .map((fieldName) => `sum(abs(ISNULL([${fieldName}],0))) as [${fieldName}] `)
      .join(','),
    pageIndex: 0,
    pageSize: consts.maxSampleCount,
    whereSql: whereSql,
  });

  if (!retData.ok) {
    showNotDataMsg(retData.data);
    /*   msgError(retData.data); */
    return getIniSampleSizeAndAmount();
  }
  sampleSizeAndAmount.sampleSize = retData.data.cnt;

  const sampledNumFields = sampleSizeAndAmount.sampledNumFields || {};

  const retInfo: any = retData.data;
  numFields.forEach((fieldName) => {
    sampledNumFields[fieldName] = { amountSum: retInfo[fieldName] };
    sampleSizeAndAmount.amountSum += retInfo[fieldName] || 0;
  });

  return sampleSizeAndAmount;
}
/**
 * 获取最大金额的wheresql
 * @param sampleStepInfo
 * @param sampleParameterValues
 */
export function getAmountMarjorWhereSql(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
) {
  const projectOverallProps = sampleStepInfo.projectOverallProps;
  let whereSql = projectOverallProps?.curSampleTable?.sampleNumFieldsArray
    ?.map((fieldName) => {
      return ` abs(ISNULL([${fieldName}],0))>=${sampleParameterValues.amountMajorMin}`;
    })
    .join(' or ');
  whereSql = ' /*getAmountMarjorWhereSql:*/ ' + ` and (${whereSql}) `;
  return whereSql;
}

/**
 * 获取 极不重要 抽样项目
 * @param sampleStepInfo
 * @param sampleParameterValues
 */

export function getUnimportantWhereSql(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
): string {
  const projectOverallProps = sampleStepInfo.projectOverallProps;

  let whereSql = projectOverallProps?.curSampleTable?.sampleNumFieldsArray
    ?.map((fieldName) => {
      return ` ( abs(ISNULL([${fieldName}],0))<>0 and  abs(ISNULL([${fieldName}],0))<=${sampleParameterValues.unimportantMax} )`;
    })
    .join(' or ');

  whereSql = ' /*getUnimportantWhereSql:*/ ' + ` and (${whereSql}) `;
  return whereSql;
}
/**
 * 获取文本字段的值,没有引号
 * @param oneSampledInfo
 * @param sampleTextFieldsArray
 * @returns
 */
export function getTextFieldsValues(
  oneSampledInfo: any /* SampledInfo */,
  sampleTextFieldsArray: string[],
) {
  let values1 = '';
  sampleTextFieldsArray.forEach((fieldName) => {
    values1 += `${oneSampledInfo[fieldName]}`;
  });
  return values1;
}

/**
 * 获取Text字段的数组
 * @param curSampleTable
 * @returns
 */
export function getSampleTextSampleFieldsArray(curSampleTable: SampleTable): SampleField[] {
  const sampleTextSampleFieldsArray: SampleField[] = curSampleTable.sampleAllFieldsArray.filter(
    (item) => curSampleTable.sampleTextFieldsArray?.includes(item.fieldName),
  );
  return sampleTextSampleFieldsArray;
}
/**
 * 获取数字 字段信息
 * @param curSampleTable
 * @returns
 */
export function getSampleNumSampleFieldsArray(curSampleTable: SampleTable): SampleField[] {
  const fieldsArray: SampleField[] = curSampleTable.sampleAllFieldsArray.filter((item) =>
    curSampleTable.sampleNumFieldsArray?.includes(item.fieldName),
  );
  return fieldsArray;
}
/**
 * 通过样本获取sql
 * @param sampleStepInfo
 * @param sampleList
 */
export async function getWhereSqlBySampleList(
  sampleStepInfo: SampleStepInfo,
  sampleList: any[],
  dbname?: string,
) {
  if (sampleList?.length == 0) return '';
  const sampleTextSampleFieldsArray: SampleField[] = getSampleTextSampleFieldsArray(
    sampleStepInfo.projectOverallProps?.curSampleTable as any,
  );

  if (sampleTextSampleFieldsArray.length == 1 && sampleList.length < 1000) {
    //一个的情况下且小1000条使用这种方式
    //改为 每一个字段用一次in ,如果用cast和+的方式,会查询很慢的
    const sqlArray: string[] = sampleTextSampleFieldsArray.map((textField) => {
      let inSql = sampleList
        .map((item) => {
          let value = item[textField.fieldName];
          return textField.isNum ? value : `'${value}'`; //数字直接使用,字符串加引号
        })
        .join(',');
      inSql = ` and [${textField.fieldName}] in (${inSql})`;
      return inSql;
    });
    return sqlArray.join(' ');
  } else {
    //多个字段,有可能抽26表显示34个
    //主表,不知道慢不慢,如果慢,可以改用 getWhereSqlBySampleListOfTable()的方法
    if (!dbname) {
      try {
        dbname = JSON.parse(sessionStorage.electronParams)?.params?.dbname;
      } catch (error) { }
    }
    if (dbname) {
      let retData = await getWhereSqlBySampleListOfTable(sampleStepInfo, sampleList, dbname);
      return retData.sampledWhereSql;
    } else {
      const mainTableName = getRealTableName(
        sampleStepInfo.projectOverallProps?.curSampleTable?.tableName || '',
        { data_id: sampleStepInfo.projectOverallProps?.curDataId || '' },
      );

      const sqlArray: string[] = sampleList.map((item, index) => {
        return (
          (index > 0 ? 'union all ' : '') +
          ' select ' +
          sampleTextSampleFieldsArray
            .map(
              (textField) =>
                `'${item[textField.fieldName]}'` + (index == 0 ? ` [${textField.fieldName}]` : ''),
            )
            .join(',')
        );
      });
      let sql = ' and exists( select 1 from (' + sqlArray.join('\n') + ') b  where   ';
      sql += sampleTextSampleFieldsArray
        .map(
          (textField) => `  [${mainTableName}].[${textField.fieldName}]=b.[${textField.fieldName}]`,
        )
        .join(' and ');
      sql += ')';
      return sql;
    }

    //使用表
  }
}
/**
 * 通过临时表来查询条件,快速
 * @param sampleStepInfo
 * @param sampleList 用程序抽出来的样本列表,未包含(重大,特殊样本)
 * @returns
 */
export async function getWhereSqlBySampleListOfTable(
  sampleStepInfo: SampleStepInfo,
  sampleList: any[],
  dbname: string,
): Promise<{ sampledWhereSql: string; notSampledWhereSql: string }> {
  if (sampleList?.length == 0) return { sampledWhereSql: '', notSampledWhereSql: '' };

  const sampleTextSampleFieldsArray: SampleField[] = getSampleTextSampleFieldsArray(
    sampleStepInfo.projectOverallProps?.curSampleTable as any,
  );

  let sample_temp_table = `sample_list_temp_${getNanoid10()}}`;

  const retData = await getNestApiData('/auditSample/createAndInsertSampleTempTable', 'POST', {
    sampleTextSampleFieldsArray,
    sampleList,
    dbname,
    sample_temp_table,
  });
  if (!retData.ok) return { sampledWhereSql: '', notSampledWhereSql: '' };

  //改为 每一个字段用一次in ,如果用cast和+的方式,会查询很慢的

  const mainTableName = getRealTableName(
    sampleStepInfo.projectOverallProps?.curSampleTable?.tableName || '',
    { data_id: sampleStepInfo.projectOverallProps?.curDataId || '' },
  );

  let existsSql = `  exists( select 1 from  [${dbname}]..[${sample_temp_table}] b  where   `;
  existsSql += sampleTextSampleFieldsArray
    .map((textField) => `  [${mainTableName}].[${textField.fieldName}]=b.[${textField.fieldName}]`)
    .join(' and ');
  existsSql += ')';

  const inSqlArray: string[] = [' and ' + existsSql];
  const notInSqlArray: string[] = [' and not ' + existsSql];
  return {
    sampledWhereSql: inSqlArray.join(''),
    notSampledWhereSql: notInSqlArray.join(),
  };
}
/**
 *
 * @param sampleStepInfo B.待抽样的测试总体(扣除特定项目后)	 SQL
 * @param sampleParameterValues
 */
export function getToBeTestWhereSql(
  //sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
) {
  //const projectOverallProps = sampleStepInfo.projectOverallProps;
  const amountMajorWhereSql = sampleParameterValues.amountMajorWhereSql || ''; //获取金额重大where
  const unimportantWhereSql = sampleParameterValues.unimportantWhereSql || ''; //获取极不重要where
  const specialWhereSql = sampleParameterValues.specialWhereSql || ''; //获取性质特殊where

  let toBeTestWhereSql = '';
  if (amountMajorWhereSql) {
    toBeTestWhereSql += ` and not (1=1 ${amountMajorWhereSql})`;
  }
  if (unimportantWhereSql) {
    toBeTestWhereSql += ` and not (1=1 ${unimportantWhereSql})`;
  }
  if (specialWhereSql) {
    toBeTestWhereSql += ` and not (1=1 ${specialWhereSql})`;
  }

  return ' /*toBeTestWhereSql:*/ ' + toBeTestWhereSql;
}

export function getRedStarHtml() {
  return <span className="red-star">*</span>;
}

/**
 * 试抽取: 获取文本字段值
 */
export async function getTrySampleResult(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
): Promise<SampledResult> {
  const projectOverallProps = sampleStepInfo.projectOverallProps;
  const curSampleTable = projectOverallProps?.curSampleTable;
  let sampledResult = getIniSampledResult();
  if (curSampleTable && sampleParameterValues.toBeTestSampleSize) {
    //随机抽样
    if (sampleParameterValues.sampleMethod == SampleMethod.random) {
      if (sampleParameterValues.randomSampleParams?.extractNumber) {
        let sampleNos: number[] = []; //样本编号
        if (sampleParameterValues.randomSampleParams?.useReproducible) {
          //
          sampleNos = getReproducibleRandomValues(
            sampleParameterValues.toBeTestSampleSize,
            sampleParameterValues.randomSampleParams?.extractNumber,
            sampleParameterValues.randomSampleParams.seed,
          );
        } else {
          sampleNos = getNotReproRandomValues(
            sampleParameterValues.toBeTestSampleSize,
            sampleParameterValues.randomSampleParams?.extractNumber,
          );
        }

        sampledResult = await getRandomOrSystemSampleList(
          sampleStepInfo,
          sampleParameterValues,
          sampleNos,
        );
      } else {
        msgError('抽取数量不能为0!');
      }
    } //PPS抽样
    else if (sampleParameterValues.sampleMethod == SampleMethod.pps) {
      if (sampleParameterValues.ppsSampleParams?.extractNumber) {
        let seed: string = '';
        if (sampleParameterValues.ppsSampleParams?.useReproducible) {
          //是否使用可重复抽取
          seed = sampleParameterValues.ppsSampleParams?.seed + ''; //固定值
        } else {
          seed = 'CHECKSUM(NEWID())'; //使用新ID,来随机
        }

        sampledResult = await getPPSSampleList(sampleStepInfo, sampleParameterValues, seed);
      } else {
        msgError('抽取数量不能为0!');
      }
    }
    //系统抽样
    else if (sampleParameterValues.sampleMethod == SampleMethod.system) {
      let sampleNos: number[] = getSystemSampleNos(
        sampleParameterValues.toBeTestSampleSize,
        sampleParameterValues.systemSampleParams?.interval || 0,
        sampleParameterValues.systemSampleParams?.extractType == SystemExtractType.asc,
      );

      if (
        sampleParameterValues.systemSampleParams &&
        !sampleParameterValues.systemSampleParams.extractNumber
      ) {
        sampleParameterValues.systemSampleParams.extractNumber = sampleNos.length;
      }
      const sortFields = getSystemSortFields(
        sampleParameterValues.systemSampleParams?.sampleSortFields || [],
      );
      sampledResult = await getRandomOrSystemSampleList(
        sampleStepInfo,
        sampleParameterValues,
        sampleNos,
        sortFields,
      );
    }
    //分层抽样
    else if (sampleParameterValues.sampleMethod == SampleMethod.layer) {
      sampledResult = await getLayerSampleList(sampleStepInfo, sampleParameterValues);
    }

    if (sampleParameterValues.sampleMethod !== SampleMethod.manual) {
      const sampleSizeAndAmount = await getSampleSizeAndAmount(
        sampleStepInfo,
        sampleParameterValues.toBeTestWhereSql,
      );
      sampledResult.sampledNumFields = { ...sampleSizeAndAmount.sampledNumFields };
    }
  } else {
    msgError('B.待抽样的测试总体(扣除特定项目后)不能为0!');
  }
  return sampledResult;
}

export async function sampleTestFor() {
  const retData = await getApiData('sample.testFor', {
    tableNames: ['CW_PZB2015', 'CW_PZB2016', 'CW_PZB2017'],
    dbname: 'FI-2017-00001',
  });
  if (!retData.ok) msgError(retData.data);
}

/**
 * 计算一个对象的大小
 * @param obj
 * @returns
 */
export function countObjectSize(obj: any): number {
  if (typeof obj !== 'object' || obj === null) {
    return 0;
  }

  let size = 0;

  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];
      if (typeof value !== 'function') {
        size += 1; // 计算当前层级的键
        size += countObjectSize(value); // 递归计算子对象的大小
      }
    }
  }

  return size;
}

//初始的抽样结果
export function getIniSampledResult() {
  const allSampledResult: SampledResult = {
    sampledSize: 0,
    sampledList: [],
    sampledAmountSum: 0,
    sampleTextFieldValues: [],
  };
  return allSampledResult;
}
/**
 * 是否需要计算分层抽样的样本
 * @param sampleParameterValues
 * @param old_toBeTestSampleSize
 * @param old_toBeTestAmountSum
 * @param old_measurementSampleSize
 * @returns
 */
export function getNeedCalcLayerSampleSize(
  sampleParameterValues: SampleParameterValues,
  old_toBeTestSampleSize: number,
  old_toBeTestAmountSum: number,
  old_measurementSampleSize: number,
) {
  const { toBeTestSampleSize, toBeTestAmountSum, measurementSampleSize } = sampleParameterValues;
  return (
    old_toBeTestSampleSize !== toBeTestSampleSize ||
    old_toBeTestAmountSum !== toBeTestAmountSum ||
    old_measurementSampleSize !== measurementSampleSize
  );
}
/**
 * 获取抽样结果表字段信息
 * @param sampleParameterValues
 * @param sampleStepInfo
 * @returns
 */
export function getSampleResultTableFieldsInfo(
  sampleParameterValues: SampleParameterValues,
  sampleStepInfo: SampleStepInfo,
) {
  const sampledResult: SampledResult = sampleParameterValues.sampledResult || getIniSampledResult();

  const { sampledList, sampledNumFields } = sampledResult;

  //数字字段
  const sampleNumSampleFieldsArray = getSampleNumSampleFieldsArray(
    sampleStepInfo.projectOverallProps?.curSampleTable as any,
  );

  const fieldsInfo = sampleNumSampleFieldsArray.map((field: SampleField) => {
    let sampledAmountSum = 0;
    const toBeTestAmountSum = sampledNumFields ? sampledNumFields[field.fieldName]?.amountSum : 0; //nonStatSampleParameter.toBeTestAmountSum || 0;//不准确
    if ([SampleMethod.manual, SampleMethod.pps].includes(sampleParameterValues.sampleMethod)) {
      //任意抽样
      sampledAmountSum = sampledList.reduce((sum, item) => {
        return sum + Math.abs(Number(item[field.fieldName] || 0));
      }, 0);
    } else {
      sampledAmountSum = sampledList
        .filter((item) => item.amountFieldName == field.fieldName)
        .reduce((sum, item) => {
          return sum + Math.abs(item.amountFieldValue || 0);
        }, 0);
    }

    const sampledAmountRate = toBeTestAmountSum ? sampledAmountSum / (toBeTestAmountSum || 0) : 0;
    return { ...field, sampledAmountSum, sampledAmountRate, toBeTestAmountSum };
  });
  return fieldsInfo;
}

/**
 * 抽样结果表(抽样结果)
 * @param sampleStepInfo
 * @param sampleParameterValues
 * @param inSamplingSampleList  是否用在 抽样样本列表界面
 * @returns
 */
export function getSampledResultTable1(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
  inSamplingSampleList?: boolean,
) {
  if (!sampleStepInfo.projectOverallProps?.curSampleTable) return;
  const sampledResult: SampledResult = sampleParameterValues.sampledResult || getIniSampledResult();
  const sampledSizeRate = sampleParameterValues.toBeTestSampleSize
    ? sampledResult.sampledSize / sampleParameterValues.toBeTestSampleSize
    : 0;
  const { sampledSize } = sampledResult;

  const fieldsInfo: any[] = getSampleResultTableFieldsInfo(sampleParameterValues, sampleStepInfo);

  const divWidth = `${100 / (fieldsInfo.length + 1)}%`;
  const fieldsContent = fieldsInfo.map((field) => {
    return (
      <div style={{ width: divWidth }}>
        <div>{`${field.fieldTitle}合计：${formatNumber(
          field.toBeTestAmountSum,
          consts.numberFormat,
        )}`}</div>
        <div>{`已抽${field.fieldTitle}：${formatNumber(
          field.sampledAmountSum,
          consts.numberFormat,
        )}`}</div>
        <div>{`所占比例：${formatNumber(field.sampledAmountRate, consts.percentFormat)}`}</div>
      </div>
    );
  });

  return (
    <div style={{ marginTop: 5, marginBottom: inSamplingSampleList ? 10 : 30 }}>
      {' '}
      {/* 30是底部工具条 上一步 下一步的高度 */}
      {/*  <div style={{ fontSize: 14, fontWeight: 'bold' }}>抽样结果</div> */}
      <div className="itemBoxDispalyLeft">
        <div style={{ width: divWidth }}>
          <div>{`总笔数：${sampleParameterValues.toBeTestSampleSize}`}</div>
          <div>{`已抽笔数：${sampledSize}`}</div>
          <div>{`所占比例：${formatNumber(sampledSizeRate, consts.percentFormat)}`}</div>
        </div>
        {fieldsContent}
      </div>
    </div>
  );
}
/**
 * 抽样结果2: 重大项目统计,特殊项目统计
 * @returns
 */
export function getSampledResultTable2(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
) {
  if (!sampleStepInfo.projectOverallProps?.curSampleTable) return;
  // const sampledResult: SampledResult = nonStatSampleParameter.sampledResult || getIniSampledResult();

  const numSampleFieldsArray: SampleField[] = getSampleNumSampleFieldsArray(
    sampleStepInfo.projectOverallProps.curSampleTable,
  );

  const divWidth = `${100 / (numSampleFieldsArray.length + 1)}%`;
  //已抽金额重大
  const amountMajorSampledNumFields = sampleParameterValues.amountMajorSampledNumFields || {};
  //已抽性质特殊
  const specialSampledNumFields = sampleParameterValues.specialSampledNumFields || {};

  const sampleListManualAddNumFields =
    sampleParameterValues.manualAddParams?.sampledNumFields || {};

  const fieldsContent = numSampleFieldsArray.map((field) => {
    return (
      <div style={{ width: divWidth }}>
        <div>{`已抽金额重大${field.fieldTitle}：${formatNumber(
          amountMajorSampledNumFields[field.fieldName]?.amountSum || 0,
          consts.numberFormat,
        )}`}</div>
        <div>{`已抽性质特殊${field.fieldTitle}：${formatNumber(
          specialSampledNumFields[field.fieldName]?.amountSum || 0,
          consts.numberFormat,
        )}`}</div>
        <div>{`手工添加样本${field.fieldTitle}：${formatNumber(
          sampleListManualAddNumFields[field.fieldName]?.amountSum || 0,
          consts.numberFormat,
        )}`}</div>
      </div>
    );
  });

  return (
    <div style={{ marginTop: 5, marginBottom: 10 }}>
      {' '}
      {/* 30是底部工具条 上一步 下一步的高度 */}
      {/*  <div style={{ fontSize: 14, fontWeight: 'bold' }}>抽样结果</div> */}
      <div className="itemBoxDispalyLeft">
        <div style={{ width: divWidth }}>
          <div>{`已抽金额重大：${sampleParameterValues.amountMajorSampleSize || 0}`}</div>
          <div>{`已抽性质特殊：${sampleParameterValues.specialSampleSize || 0}`}</div>
          <div>{`手工添加样本：${sampleParameterValues.manualAddParams?.sampledSize || 0}`}</div>
          {/* <div >{`所占比例：${formatNumber(sampledSizeRate, consts.percentFormat4Bit)}`}</div> */}
        </div>
        {fieldsContent}
      </div>
    </div>
  );
}
/**
 * 计算特殊样本信息
 * @param sampleStepInfo
 * @param sampleParameterValues
 * @param newSpecialSampleList
 */
export async function calcSpecialSampleInfo(
  sampleStepInfo: SampleStepInfo,
  sampleParameterValues: SampleParameterValues,
  newSpecialSampleList: any[],
  showMsgInfo: boolean,
  calcAmountSampleSize?: () => void,
) {
  // nonStatSampleParameter.specialSampleList = newSpecialSampleList;
  let sampleSizeAndAmount;
  if (newSpecialSampleList.length == 0) {
    sampleParameterValues.specialWhereSql = '';
    sampleSizeAndAmount = getIniSampleSizeAndAmount();
  } else {
    sampleParameterValues.specialWhereSql =
      ' /*specialWhereSql:*/' +
      (await getWhereSqlBySampleList(sampleStepInfo, newSpecialSampleList));
    sampleSizeAndAmount = await getSampleSizeAndAmount(
      sampleStepInfo,
      sampleParameterValues.specialWhereSql,
    );
  }

  sampleParameterValues.specialSampleSize = sampleSizeAndAmount.sampleSize; //newSpecialSampleList.length;
  sampleParameterValues.specialAmountSum = sampleSizeAndAmount.amountSum;

  //增加specialSampledNumFields的值
  if (!sampleParameterValues.specialSampledNumFields) {
    sampleParameterValues.specialSampledNumFields = {};
  }
  let lessThanUnimportantMaxSampleSize = 0; //属于极不重要上限的个数
  let lessThanUnimportantMaxSampleSum = 0; //属于极不重要上限的个数
  let greaterThanAmountMajorMinSampleSize = 0; //属于等于金额重大下限的个数
  let greaterThanAmountMajorMinSampleSum = 0; //属于等于金额重大下限的金额

  const specialSampledNumFields = sampleParameterValues.specialSampledNumFields;
  const numFields = sampleStepInfo.projectOverallProps?.curSampleTable?.sampleNumFieldsArray || [];
  numFields.forEach((fieldName) => {
    const sampledAmountSum = newSpecialSampleList.reduce((sum, item) => {
      const value = Math.abs(Number(item[fieldName] || 0));
      //如果小于极不重要上限
      if (
        value &&
        sampleParameterValues.unimportantMax &&
        value <= sampleParameterValues.unimportantMax
      ) {
        lessThanUnimportantMaxSampleSize++;
        lessThanUnimportantMaxSampleSum += value;
      }
      //大于等于金额重大下限的个数
      if (
        value &&
        sampleParameterValues.amountMajorMin &&
        value >= sampleParameterValues.amountMajorMin
      ) {
        greaterThanAmountMajorMinSampleSize++;
        greaterThanAmountMajorMinSampleSum += value;
      }
      return sum + value;
    }, 0);
    specialSampledNumFields[fieldName] = { amountSum: sampledAmountSum };
  });
  if (showMsgInfo) {
    let msg = '';
    if (lessThanUnimportantMaxSampleSize) {
      msg += `有 ${lessThanUnimportantMaxSampleSize} 个属于极不重要项目`;
    }
    if (greaterThanAmountMajorMinSampleSize) {
      msg += (msg ? ',' : '') + `有 ${greaterThanAmountMajorMinSampleSize} 个属于金额重大项目`;
    }
    if (msg) {
      msgError(msg);
    }
  }
  sampleParameterValues.lessThanUnimportantMaxSampleSize = lessThanUnimportantMaxSampleSize;
  sampleParameterValues.lessThanUnimportantMaxSampleSum = lessThanUnimportantMaxSampleSum;
  sampleParameterValues.greaterThanAmountMajorMinSampleSize = greaterThanAmountMajorMinSampleSize;
  sampleParameterValues.greaterThanAmountMajorMinSampleSum = greaterThanAmountMajorMinSampleSum;

  calcAmountSampleSize && calcAmountSampleSize();
}
/**
 * 统计抽样的
 * @returns
 */
export function getStatSampleMethodList() {
  return Object.values(SampleMethod).filter((item) => [SampleMethod.system].includes(item));
}
/**
 * 非统计抽样的
 * @returns
 */
export function getNonStatSampleMethodList() {
  return Object.values(SampleMethod).filter((item) => item != SampleMethod.pps);
}

export function getValueTextTop500(sampleTextFieldValues?: string[]) {
  if (!sampleTextFieldValues) return '';
  return sampleTextFieldValues.length > 1000
    ? sampleTextFieldValues.slice(0, 1000).join('、') + `等 ${sampleTextFieldValues.length} 个`
    : sampleTextFieldValues.join('、');
}
/**清除样本编辑参数,为了 只修改样本规模时,才重新计算
 */
export function clearPropsSampleParameterValues(
  propsSampleParameterValues?: SampleParameterValues,
) {
  if (propsSampleParameterValues?.randomSampleParams) {
    propsSampleParameterValues.randomSampleParams.extractNumber = 0;
  }
  if (propsSampleParameterValues?.ppsSampleParams) {
    propsSampleParameterValues.ppsSampleParams.extractNumber = 0;
  }
  if (propsSampleParameterValues?.layerSampleParams?.layerRanges) {
    propsSampleParameterValues.layerSampleParams.layerRanges.length = 0;
  }
  if (propsSampleParameterValues?.systemSampleParams) {
    propsSampleParameterValues.systemSampleParams.extractNumber = 0;
  }
}
